<?php
/**
 * Created by PhpStorm.
 * User: surestdeng
 * Date: 2019/12/23
 * Time: 16:36:09
 */

namespace App\Services;

use App\Models\Article;
use App\Repositories\Handler\LearnkuHandler;
use Illuminate\Support\Arr;
use QL\QueryList;

class LearnkuService
{
    public function run()
    {
        $urls = config('address.Learnku.list');

        foreach ($urls as $url => $tag) {
            $data = QueryList::Query($url, [
                'avatar' => ['.user-avatar>.rm-tdu>.topic-list-author-avatar', 'src'],
                'title' => ['.topic-title-wrap>.topic-title', 'text'],
                'url' => ['.topic-title-wrap', 'href']
            ])->data;

            # 过滤
            $data = array_map(function ($item){
                $item['title'] = compress_html($item['title']);
                return $item;
            }, $data);

            $learkn = new LearnkuHandler();
            $articles = $learkn->handle($data, 'Learnku');
            $this->insert($articles, $learkn, $tag);
        }
    }

    public function insert(array $articles, LearnkuHandler $learnkuHandler, $tag)
    {
        logEcho($articles, 'learnku.log');
        Article::query()->insert($articles);

        $learnkuHandler->save($articles);
        $learnkuHandler->saveTag($articles, $tag);
    }
}
